package xtrace

import (
	"context"
	"fmt"
	"strings"
	"sync"

	"gitee.com/xfrm/middleware/xconfig"
	"gitee.com/xfrm/middleware/xlog"
)

var initApolloLock = &sync.Mutex{}

var apolloCenter xconfig.ConfigCenter

var apolloSpanFilterConfig *spanFilterConfig

func initApolloCenter(ctx context.Context) error {
	if apolloCenter != nil {
		return nil
	}

	initApolloLock.Lock()
	defer initApolloLock.Unlock()

	if apolloCenter != nil {
		return nil
	}

	xlog.Infof(ctx, "initApolloCenter --> xtrace apollo center not found, init")

	return initGlobalApolloCenterWithoutLock(ctx)
}

func initGlobalApolloCenterWithoutLock(ctx context.Context) error {
	namespaceList := []string{xconfig.DefaultTraceNamespace}
	newCenter, err := xconfig.NewConfigCenter(ctx, xconfig.ConfigTypeApollo, "", xconfig.DefaultMiddlewareService, namespaceList)
	if err != nil {
		return fmt.Errorf("init apollo with service %s namespace %s error, %s",
			xconfig.DefaultMiddlewareService, strings.Join(namespaceList, " "), err.Error())
	}

	apolloCenter = newCenter
	xlog.Infof(ctx, "initApolloCenter --> initGlobalApolloCenter success")
	return nil
}
